<template>
  <div class="space-y-6">
    <div class="flex justify-between items-center">
      <div>
        <h1 class="text-3xl font-bold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
          {{ isEdit ? '编辑审判' : '新增审判' }}
        </h1>
        <div class="text-sm breadcrumbs mt-1">
          <ul>
            <li><a @click="router.push('/')">首页</a></li>
            <li><a @click="router.push('/judgments')">审判管理</a></li>
            <li>{{ isEdit ? '编辑审判' : '新增审判' }}</li>
          </ul>
        </div>
      </div>
      <div class="flex gap-2">
        <button class="btn btn-ghost" @click="handleCancel">取消</button>
        <button
          class="btn btn-primary"
          :class="{ loading: isSubmitting }"
          @click="handleSubmit"
        >
          保存
        </button>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 基本信息 -->
      <div class="card bg-base-100 shadow-xl lg:col-span-2">
        <div class="card-body">
          <h2 class="card-title">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 1.944A11.954 11.954 0 012.166 5C2.056 5.649 2 6.319 2 7c0 5.225 3.34 9.67 8 11.317C14.66 16.67 18 12.225 18 7c0-.682-.057-1.35-.166-2.001A11.954 11.954 0 0110 1.944zM11 14a1 1 0 11-2 0 1 1 0 012 0zm0-7a1 1 0 10-2 0v3a1 1 0 102 0V7z" clip-rule="evenodd" />
            </svg>
            基本信息
          </h2>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="form-control">
              <label class="label">
                <span class="label-text font-medium">案件编号</span>
                <span class="label-text-alt text-error">*</span>
              </label>
              <input
                type="text"
                v-model="formData.caseNumber"
                placeholder="请输入案件编号"
                class="input input-bordered"
                :class="{ 'input-error': errors.caseNumber }"
                @blur="validateField('caseNumber')"
              />
              <label class="label" v-if="errors.caseNumber">
                <span class="label-text-alt text-error">{{ errors.caseNumber }}</span>
              </label>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text font-medium">魂魄姓名</span>
                <span class="label-text-alt text-error">*</span>
              </label>
              <input
                type="text"
                v-model="formData.soulName"
                placeholder="请输入魂魄姓名"
                class="input input-bordered"
                :class="{ 'input-error': errors.soulName }"
                @blur="validateField('soulName')"
              />
              <label class="label" v-if="errors.soulName">
                <span class="label-text-alt text-error">{{ errors.soulName }}</span>
              </label>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text font-medium">审判官</span>
                <span class="label-text-alt text-error">*</span>
              </label>
              <select
                v-model="formData.judge"
                class="select select-bordered"
                :class="{ 'select-error': errors.judge }"
                @blur="validateField('judge')"
              >
                <option value="">请选择审判官</option>
                <option value="阎王">阎王</option>
                <option value="判官">判官</option>
                <option value="黑白无常">黑白无常</option>
              </select>
              <label class="label" v-if="errors.judge">
                <span class="label-text-alt text-error">{{ errors.judge }}</span>
              </label>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text font-medium">审判时间</span>
                <span class="label-text-alt text-error">*</span>
              </label>
              <input
                type="datetime-local"
                v-model="formData.judgmentTime"
                class="input input-bordered"
                :class="{ 'input-error': errors.judgmentTime }"
                @blur="validateField('judgmentTime')"
              />
              <label class="label" v-if="errors.judgmentTime">
                <span class="label-text-alt text-error">{{ errors.judgmentTime }}</span>
              </label>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text font-medium">判决结果</span>
              </label>
              <select
                v-model="formData.result"
                class="select select-bordered"
                :class="{ 'select-error': errors.result }"
                @blur="validateField('result')"
              >
                <option value="">请选择判决结果</option>
                <option value="reincarnation">转世投胎</option>
                <option value="hell">打入地狱</option>
                <option value="heaven">直升天堂</option>
              </select>
              <label class="label" v-if="errors.result">
                <span class="label-text-alt text-error">{{ errors.result }}</span>
              </label>
            </div>
            <div class="form-control">
              <label class="label">
                <span class="label-text font-medium">状态</span>
                <span class="label-text-alt text-error">*</span>
              </label>
              <select
                v-model="formData.status"
                class="select select-bordered"
                :class="{ 'select-error': errors.status }"
                @blur="validateField('status')"
              >
                <option value="">请选择状态</option>
                <option value="pending">待审判</option>
                <option value="processing">审判中</option>
                <option value="completed">已完成</option>
              </select>
              <label class="label" v-if="errors.status">
                <span class="label-text-alt text-error">{{ errors.status }}</span>
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- 状态信息 -->
      <div class="space-y-6">
        <div class="card bg-base-100 shadow-xl">
          <div class="card-body">
            <h2 class="card-title">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
              </svg>
              状态信息
            </h2>
            <div class="space-y-4">
              <div class="form-control">
                <label class="label">
                  <span class="label-text font-medium">功德值</span>
                </label>
                <input
                  type="number"
                  v-model="formData.merit"
                  placeholder="请输入功德值"
                  class="input input-bordered"
                  :class="{ 'input-error': errors.merit }"
                  @blur="validateField('merit')"
                />
                <label class="label" v-if="errors.merit">
                  <span class="label-text-alt text-error">{{ errors.merit }}</span>
                </label>
              </div>
              <div class="form-control">
                <label class="label">
                  <span class="label-text font-medium">罪孽值</span>
                </label>
                <input
                  type="number"
                  v-model="formData.sin"
                  placeholder="请输入罪孽值"
                  class="input input-bordered"
                  :class="{ 'input-error': errors.sin }"
                  @blur="validateField('sin')"
                />
                <label class="label" v-if="errors.sin">
                  <span class="label-text-alt text-error">{{ errors.sin }}</span>
                </label>
              </div>
              <div class="form-control">
                <label class="label">
                  <span class="label-text font-medium">轮回次数</span>
                </label>
                <input
                  type="number"
                  v-model="formData.reincarnationCount"
                  placeholder="请输入轮回次数"
                  class="input input-bordered"
                  :class="{ 'input-error': errors.reincarnationCount }"
                  @blur="validateField('reincarnationCount')"
                />
                <label class="label" v-if="errors.reincarnationCount">
                  <span class="label-text-alt text-error">{{ errors.reincarnationCount }}</span>
                </label>
              </div>
            </div>
          </div>
        </div>

        <div class="card bg-base-100 shadow-xl">
          <div class="card-body">
            <h2 class="card-title">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M18 13V5a2 2 0 00-2-2H4a2 2 0 00-2 2v8a2 2 0 002 2h3l3 3 3-3h3a2 2 0 002-2zM5 7a1 1 0 011-1h8a1 1 0 110 2H6a1 1 0 01-1-1zm1 3a1 1 0 100 2h3a1 1 0 100-2H6z" clip-rule="evenodd" />
              </svg>
              备注信息
            </h2>
            <div class="form-control">
              <textarea
                v-model="formData.remarks"
                class="textarea textarea-bordered h-24"
                placeholder="请输入备注信息"
              ></textarea>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { JudgmentService, SoulService } from '@/api/services'
import { useLoadingStore } from '@/stores/loading'
import { useToast } from '@/composables/useToast'

const route = useRoute()
const router = useRouter()
const loadingStore = useLoadingStore()
const toast = useToast()

const id = route.params.id as string
const isEdit = computed(() => !!id)
const isSubmitting = ref(false)

interface FormData {
  caseNumber: string
  soulName: string
  judge: string
  judgmentTime: string
  result: string
  status: string
  merit: number | null
  sin: number | null
  reincarnationCount: number | null
  remarks: string
}

const formData = ref<FormData>({
  caseNumber: '',
  soulName: '',
  judge: '',
  judgmentTime: '',
  result: '',
  status: '',
  merit: null,
  sin: null,
  reincarnationCount: null,
  remarks: '',
})

const errors = ref<Record<string, string>>({})

type ValidationRule<T> = (value: T) => true | string

interface ValidationRules {
  caseNumber: ValidationRule<string>[]
  soulName: ValidationRule<string>[]
  judge: ValidationRule<string>[]
  judgmentTime: ValidationRule<string>[]
  result: ValidationRule<string>[]
  status: ValidationRule<string>[]
  merit: ValidationRule<number | null>[]
  sin: ValidationRule<number | null>[]
  reincarnationCount: ValidationRule<number | null>[]
}

const validationRules: ValidationRules = {
  caseNumber: [
    (v: string) => !!v || '请输入案件编号',
    (v: string) => v.length <= 20 || '案件编号不能超过20个字符',
  ],
  soulName: [
    (v: string) => !!v || '请输入魂魄姓名',
    (v: string) => v.length <= 20 || '魂魄姓名不能超过20个字符',
  ],
  judge: [(v: string) => !!v || '请选择审判官'],
  judgmentTime: [(v: string) => !!v || '请选择审判时间'],
  result: [() => true],
  status: [(v: string) => !!v || '请选择状态'],
  merit: [
    (v: number | null) => v === null || (v >= 0 && v <= 100) || '功德值必须在0-100之间',
  ],
  sin: [
    (v: number | null) => v === null || (v >= 0 && v <= 100) || '罪孽值必须在0-100之间',
  ],
  reincarnationCount: [
    (v: number | null) => v === null || v >= 0 || '轮回次数不能为负数',
  ],
}

type FormFields = keyof ValidationRules
type FormValue<T extends FormFields> = T extends keyof FormData ? FormData[T] : never

const validateField = <T extends FormFields>(field: T) => {
  const rules = validationRules[field] as ValidationRule<FormValue<T>>[]
  let isValid = true

  for (const rule of rules) {
    const result = rule(formData.value[field] as FormValue<T>)
    if (result !== true) {
      errors.value[field] = result
      isValid = false
      break
    }
  }

  if (isValid) {
    delete errors.value[field]
  }

  return isValid
}

const validateForm = () => {
  let isValid = true
  for (const field in validationRules) {
    if (!validateField(field as FormFields)) {
      isValid = false
    }
  }
  return isValid
}

const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  isSubmitting.value = true
  try {
    loadingStore.show()

    if (isEdit.value) {
      const { caseNumber, soulName, judge, judgmentTime, result, status, merit, sin, reincarnationCount, remarks } = formData.value
      await JudgmentService.updateJudgment(id, {
        caseNumber,
        soulName,
        judge,
        judgmentTime,
        result,
        status,
        merit,
        sin,
        reincarnationCount,
        remarks,
      })
      toast.success('修改成功')
    } else {
      await JudgmentService.createJudgment(formData.value)
      toast.success('创建成功')
    }

    router.push('/judgments')
  } catch (error: any) {
    toast.error(error.message)
  } finally {
    isSubmitting.value = false
    loadingStore.hide()
  }
}

const handleCancel = () => {
  router.back()
}

onMounted(async () => {
  if (!isEdit.value) {
    try {
      // TODO: 从API获取审判详情
      await new Promise((resolve) => setTimeout(resolve, 1000))
      formData.value = {
        caseNumber: 'JD2024030901',
        soulName: '张三',
        judge: '阎王',
        judgmentTime: '2024-03-09T10:30',
        result: 'reincarnation',
        status: 'processing',
        merit: 78,
        sin: 23,
        reincarnationCount: 3,
        remarks: '',
      }
    } catch (error) {
      console.error('获取审判详情失败:', error)
    }
  }
})
</script>

<style scoped>
.badge {
  @apply px-2 py-1;
}
</style>
